import uuid

from django.contrib.auth.hashers import make_password, check_password
from django.contrib.auth.models import AbstractUser
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.db.models import Q, SET_NULL
from django.utils import timezone

from apps.DepartManagement.models import Department


class UserQuerySet(models.QuerySet):
    def filter_by_status(self, status):
        """
        根据 status 字段过滤用户
        """
        return self.filter(status=status)

    def filter_by_keywords(self, keywords):
        """
        根据 keywords (username 或 name) 进行模糊查询
        """
        return self.filter(
            Q(username__icontains=keywords) | Q(name__icontains=keywords)
        )

    def filter_by_status_and_keywords(self, status, keywords):
        """
        根据 status 和 keywords (username 或 name) 组合查询
        """
        return self.filter(
            Q(status=status) & (Q(username__icontains=keywords) | Q(name__icontains=keywords))
        )


class UserManager(models.Manager):
    def get_queryset(self):
        return UserQuerySet(self.model, using=self._db)  # 返回自定义的 QuerySet

    def filter_by_status(self, status):
        return self.get_queryset().filter_by_status(status)

    def filter_by_keywords(self, keywords):
        return self.get_queryset().filter_by_keywords(keywords)

    def filter_by_status_and_keywords(self, status, keywords):
        return self.get_queryset().filter_by_status_and_keywords(status, keywords)


# 用户模型
class User(AbstractUser):
    class Meta:
        db_table = 'user'
    objects = UserManager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)
    # 用户名
    username = models.CharField(max_length=30, unique=True, help_text='用户名')
    # 密码
    password = models.CharField(max_length=255, help_text='用户密码')
    # 用户姓名
    name = models.CharField(max_length=30, help_text='用户姓名')
    # 类型
    USER_TYPE = (
        (0, "user"),
        (1, "admin"),
    )
    user_type = models.IntegerField(
        choices=USER_TYPE, default=0, verbose_name="用户类型", null=True, blank=True, help_text="用户类型"
    )
    # 是否活跃
    status = models.BooleanField(default=True, help_text='是否激活')
    # 电话
    phone = models.CharField(max_length=20, null=True, blank=True, help_text='电话号码')
    # Email
    email = models.EmailField(max_length=255, null=True, blank=True, help_text='邮箱账号')
    # 创建时间
    create_time = models.DateTimeField(default=timezone.now, help_text='创建时间')
    # 更新时间
    update_time = models.DateTimeField(auto_now=True, help_text='更新时间')

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = [
        'password'
    ]

    depart = models.ForeignKey(Department, max_length=30, on_delete=SET_NULL, null=True, blank=True,
                               related_name='user', help_text='所属部门')

    @property
    def is_authenticated(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def set_password(self, raw_password):
        self.password = make_password(raw_password)

    def check_password(self, raw_password):
        return check_password(raw_password, self.password)


class File(models.Model):
    class Meta:
        db_table = 'file'
    objects = models.Manager
    file = models.FileField(upload_to='uploads/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.file.name


class WrongQuestions(models.Model):
    objects = models.Manager
    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='wrong_questions')
    question = models.ForeignKey('QuestionManagement.Questions', on_delete=models.CASCADE,
                                 related_name='wrong_questions')
    solution = models.TextField(max_length=500, blank=True, null=True, help_text='学生作答结果')
    score = models.IntegerField(default=0, help_text='试题得分')
    wrong_time = models.DateTimeField(help_text='错误时间')
    wrong_number = models.IntegerField(default=1, help_text='错误次数')
    mastery = models.IntegerField(default=80, validators=[MinValueValidator(0), MaxValueValidator(100)],
                                  help_text='掌握程度')
    created_at = models.DateTimeField(default=timezone.now, help_text='创建时间')
    updated_at = models.DateTimeField(auto_now=True, help_text='更新时间')

    class Meta:
        db_table = 'wrong_questions'
